<?php

/**
 * Initialize the system
 */
define('TL_MODE', 'FE');
require('system/initialize.php');

class BackPocketAction extends Controller
{
	/**
	 * This is class construct function.
	 * @params null
	 * @Return null
	 */
	public function __construct()
	{
		parent::__construct();		
	}
	
	public function addToCart()
	{
		$id			= $_POST['id'];
		$skuid		= $_POST['skuid'];
		$name		= $_POST['prodcut_name'];
		$gwPrice	= ($_POST['wrapping_price']) ? number_format(floatval($_POST['wrapping_price']), 2, '.', '') : '0.00';
		$price		= number_format(floatval($_POST['price']), 2, '.', '');
		$colour		= $_POST['colour'];
		$size		= $_POST['size'];	
		$quantity	= $_POST['quantity'];
		$colour_ids	= $_POST['colour_ids'];
		$size_ids	= $_POST['size_ids'];
		$is_wrapping = intval($_POST['is_wrapping']) ? intval($_POST['is_wrapping']) : '0';
		$is_overstock = false;
		
		$stock = 0;
		// Get the stock information of this special product.
		$strSQL = "SELECT `tl_catalog_attribute`.*, catalog_colour.title  
					FROM `tl_catalog_attribute` 
					LEFT JOIN `catalog_colour` ON `catalog_colour`.id=`tl_catalog_attribute`.id_color
					WHERE `tl_catalog_attribute`.`id_catalog`=? AND `catalog_colour`.`title`=? AND `tl_catalog_attribute`.`id_size`=?";
		$this->import("Database");
		$objStock = $this->Database->prepare($strSQL)
									->execute($id, $colour, $size, time(), time());
		if ($objStock->numRows < 1)
		{
			echo 0;exit;
		}
		$stock = intval($objStock->catalog_stock);
		$currentQuantity = 0;
		
		if (!$stock)
		{
			echo 0;exit;
		}
		else 
		{
			$sessionID	= $id."_".$size."_".trim(strtolower($colour));
			
			$currentQuantity = 0;			
			if(isset($_SESSION['cart'][$sessionID]))
			{
				$is_overstock = true;
				$currentQuantity = 0;
					
				/*$_SESSION['cart'][$sessionID]['gift_wrapping'] = ($is_wrapping) ? $is_wrapping : 0;
				$_SESSION['cart'][$sessionID]['price'] = $price;
				if($_SESSION['cart'][$sessionID]['quantity'] < $stock)
				{
					$is_overstock = false;
					$_SESSION['cart'][$sessionID]['quantity'] += $quantity;
					if ($_SESSION['cart'][$sessionID]['quantity'] > $stock)
					{
						$_SESSION['cart'][$sessionID]['quantity'] = $stock;
						$currentQuantity = $stock - $_SESSION['cart'][$sessionID]['quantity'] + $quantity;
					}
					else
					{
						$currentQuantity = $quantity;
					}
				}
				else
				{
					$is_overstock = true;
					$currentQuantity = 0;
					
				}*/
			}else{
				$is_overstock = false;
				if ($quantity <= $stock)
				{
					$currentQuantity = $quantity;
					$_SESSION['cart'][$sessionID] = array(
						"id"		=> $id,
						"skuid"		=> $skuid,
						"name"		=> $name,
						"price"		=> $price,
						"colour"	=> $colour,
						"size"		=> $size,
						"quantity"	=> $currentQuantity,
						"colour_ids"=> $colour_ids,
						"size_ids"	=> $size_ids,
						"gift_wrapping" => $is_wrapping,
						'gwPrice'	=> $gwPrice
					);
				}
				else
				{
					$is_overstock = true;
					$currentQuantity = 0;
				}				
			}
			
			// Discount the stock of the product.				
			/*$objStock = $this->Database->prepare("Update tl_catalog_attribute SET catalog_stock=catalog_stock-" . $quantity . " WHERE id_catalog=? AND id_color=? AND id_size=?")
										->execute($id, $colour, $size);*/
			
			if (!isset($_SESSION['CARTQUANTITY']) || !$_SESSION['CARTQUANTITY'])
				$_SESSION['CARTQUANTITY'] = 0;
			
			$_SESSION['CARTQUANTITY'] = intval($_SESSION['CARTQUANTITY']) + $currentQuantity;
			
			$res = '[{"status" : ' . (($is_overstock) ? '1' : '0') . ', "quantity" : ' . $_SESSION['CARTQUANTITY'] . '}]';
			echo $res;			
		}
	}
	
	public function updateCart()
	{
		$id_backpocket	= $_POST['id_backpocket'];
		$id				= $_POST['id'];
		$old_sessionID	= $_POST['session_id'];
		$colour		= $_POST['colour'];
		$size		= $_POST['size'];
		$id_member	= $_POST['id_member'];
		$quantity	= $_POST['quantity'];	
		
		$sessionID	= $id."_".$size."_".trim(strtolower($colour));
		// Change the backpocket information.
		$this->import("Database");
		
		$stock = 0;
		// Get the stock information of this special product.
		$strSQL = "SELECT `tl_catalog_attribute`.*, catalog_colour.title  
					FROM `tl_catalog_attribute` 
					LEFT JOIN `catalog_colour` ON `catalog_colour`.id=`tl_catalog_attribute`.id_color
					WHERE `tl_catalog_attribute`.`id_catalog`=? AND `catalog_colour`.`title`=? AND `tl_catalog_attribute`.`id_size`=?";
		$this->import("Database");
		$objStock = $this->Database->prepare($strSQL)
									->execute($id, $colour, $size, time(), time());
		if ($objStock->numRows < 1)
		{
			echo 0;exit;
		}
		$stock = intval($objStock->catalog_stock);
		
		if (!$stock)
		{
			echo '0';exit;
		}
		else 
		{
			if ($quantity > $stock)
				$is_overstock = true;
			else
				$is_overstock = false;
			
			if (!$is_overstock)
			{
				$objBackPacket = $this->Database->prepare("SELECT * FROM `tl_backpocket` WHERE `size`=? AND `color`=? AND `id_member`=?")
											->execute($size, $colour, $id_member);
				
				if ($objBackPacket->numRows > 0)
				{
					if ($objBackPacket->id_backpocket == $id_backpocket)
					{
						$objPacket = $this->Database->prepare("UPDATE `tl_backpocket` SET `size`=?, `color`=?, `quantity`=? WHERE `id_backpocket`=?")
												->execute($size, $colour, $quantity, $id_backpocket);
					}
					else
					{
						$objPacket = $this->Database->prepare("UPDATE `tl_backpocket` SET `size`=?, `color`=?, `quantity`=? WHERE `id_backpocket`=?")
													->execute($size, $colour, $objBackPacket->quantity + $quantity, $objBackPacket->id_backpocket);
						$objPacket = $this->Database->prepare("DELETE FROM `tl_backpocket` WHERE `id_backpocket`=?")
													->execute($id_backpocket);
					}
				}
				else
				{
					$objPacket = $this->Database->prepare("UPDATE `tl_backpocket` SET `size`=?, `color`=?, `quantity`=? WHERE `id_backpocket`=?")
												->execute($size, $colour, $quantity, $id_backpocket);
				}
				
				echo "updated=success::session_id=" . $sessionID;exit;
			}
			else
			{
				echo 'false';
			}
		}
	}	
	
	public function removeFromPocket()
	{
		// remove.
		$id_backpocket = $_POST['id_backpocket'];
		
		$this->import("Database");
		$objPacket = $this->Database->prepare("DELETE FROM `tl_backpocket` WHERE `id_backpocket`=?")
									->execute($id_backpocket);
		echo 'success';
	}	
}

$action = $_REQUEST['FORM_SUBMIT'];

$cart	= new BackPocketAction();

switch($action){
	case "addtocart":
		$cart->addToCart();
		break;
	case "updatebackpocket":
		$cart->updateCart();
		break;
	case "removefrombackpocket":
		$cart->removeFromPocket();
		break;		
}
?>